package com.gitee.zhziyun.meowchat.meowserver;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gitee.zhziyun.meowchat.common.model.*;
import com.gitee.zhziyun.meowchat.meowserver.dao.UserDaoImpl;
import com.gitee.zhziyun.meowchat.meowserver.entity.User;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.BlockingQueue;

/* worker与每个用户一一对应，用于与用户交互 */
public class MeowWorker implements Runnable {
    private final Socket sk;                    // 与客户端的套接字连接
    private final ObjectMapper objectMapper;          // 用于json字符串与对象之间的转换
    private final UserDaoImpl userDaoImpl;                 // 用于与用户表交互
    private final Queue<String> receiveMessageQueue;       // 消息队列
    private final Queue<String> sendMessageQueue;       // 消息队列
    private int userId;

    public MeowWorker(Socket sk, BlockingQueue<String> msgQueue) {              // 初始化当前worker
        this.sk = sk;
        objectMapper = new ObjectMapper();
        userDaoImpl = new UserDaoImpl();
        this.receiveMessageQueue = new LinkedList<String>();
        this.sendMessageQueue = msgQueue;
        this.userId = -1;
    }

    @Override
    public void run() {
        try {
            PrintWriter out = new PrintWriter(sk.getOutputStream(), true);              // 向客户端的输出流
            BufferedReader in = new BufferedReader(new InputStreamReader(sk.getInputStream()));  // 来自客户端的输入流

            /* 主循环 */
            while (true) {
                /* 处理客户端输入 */
                if (in.ready()) {
                    Command command = objectMapper.readValue(in.readLine(), Command.class);   // 从输入流中读取一条信息，并转换成Massage对象

                    switch (command.getOption()) {                                      // 根据option中的操作来执行不同的行为
                        case "login":                                                   // 登录操作
                            login(out, command.getData());
                            break;
                        case "register":                                                // 注册操作
                            register(out, command.getData());
                            break;
                        case "logout":
                            break;
                        case "sendMsg":
                            sendMsg(command.getData());
                            break;
//                        case "sendToClient":
//                            break;
                        case "exit":
                            break;
                        default:
                            System.out.println("未知操作！");
                    }
                }

                /* 向客户端输出 */
                String msg = receiveMessageQueue.poll();
                if (msg != null) {
                    sendToClient(out, msg);
                }
            }

        } catch (IOException e) {
            System.out.println("连接断开");
        }
    }

    public int getUserId() {
        return userId;
    }

    /* 登陆验证 */
    private boolean login(PrintWriter out, String data) throws JsonProcessingException {
        boolean isLogin = false;
        String msg;

        /* 检验用户密码 */
        try {
            Identity identity = objectMapper.readValue(data, Identity.class);
            User user = userDaoImpl.findByName(identity.getUsername());
            if (user != null && user.getPassword().equals(identity.getPassword())) {
                msg = "登录成功！";
                isLogin = true;
                this.userId = user.getId();
            } else {
                msg = "登录失败！";
            }
        } catch (Exception e) {
            msg = e.toString();
        }

        /* 向客户端返回登陆结果 */
        out.println(objectMapper.writeValueAsString(
                new Command("loginRes", objectMapper.writeValueAsString(
                        new Result(isLogin, msg)
                ))
        ));

        return isLogin;     // 返回登陆结果
    }
    /* 注册用户 */
    private boolean register(PrintWriter out, String data) throws JsonProcessingException {
        boolean isRegistered = false;
        String msg;

        try {
            Identity identity = objectMapper.readValue(data, Identity.class);
            if (userDaoImpl.add(identity.getUsername(), identity.getPassword())) {
                msg = "注册成功！";
            } else {
                msg = "用户已存在！";
            }
        } catch (Exception e) {
            msg = e.toString();
        }

        out.println(objectMapper.writeValueAsString(
                new Command("registerRes", objectMapper.writeValueAsString(
                        new Result(isRegistered, msg)
                ))
        ));
        return isRegistered;
    }
    /* 退出登陆 */
    private void logout() {}
    /* 发送信息 */
    private void sendMsg(String msg) {
        System.out.println(sendMessageQueue.offer(msg));

    }
    /* 发送信息到客户端 */
    private void sendToClient(PrintWriter out, String msg) throws JsonProcessingException {
        out.println(objectMapper.writeValueAsString(new Command("receive", msg)));
    }

    public void receiveMsg(String msg) {
        receiveMessageQueue.add(msg);
    }
}
